package homework.scp;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

public class FtpClient {

	public static void main(String[] args) throws Exception {
		String[] command = null;
		InputStream in = null;
		OutputStream out = null;
		Socket socket = null;
		BufferedReader reader = null;
		System.out.println("Please input command...\n");
		Scanner scanner = new Scanner(System.in);
		command = scanner.nextLine().split("\\s+");
		File file = new File(command[1]);
		while (!(file.exists() && command[0].equals("SCP"))) {
			System.out.println("Error,please input again...");
			command = scanner.nextLine().split("\\s+");
			file = new File(command[1]);
		}
		socket = new Socket(command[2].substring(0, command[2].indexOf(":")), 8001);
		in = socket.getInputStream();
		out = socket.getOutputStream();
		reader = new BufferedReader(new InputStreamReader(in));
		if (reader.readLine().equals("ready")) {
			String sourceFileName = command[1].substring(command[1].lastIndexOf('\\'));
			out.write((sourceFileName + "\n").getBytes());
			out.write((command[2] + "\n").getBytes());
		}
	
		

//		String filePath = command[1];
//		File file = new File(filePath);
//		System.out.println(filePath);
		InputStream fin=new FileInputStream(file);
		byte[] buf=new byte[4];
		int len=0;
		while ((len=fin.read(buf))!=-1) {
			out.write(buf,0,len);
			
		}
		
		

		out.close();
		reader.close();
		fin.close();
		socket.close();
		

	}

}
